package com.leesche.zcsp.node.web.controller.web.operation;

import com.leesche.zcsp.node.app.v1.vo.FactoryDeviceVo;
import com.leesche.zcsp.node.utils.*;
import com.leesche.zcsp.node.utils.web.PagingResult;
import com.leesche.zcsp.node.utils.web.messge.WebResult;
import com.leesche.zcsp.node.web.model.PubDeviceShortCode;
import com.leesche.zcsp.node.web.model.PubPaymentURL;
import com.leesche.zcsp.node.web.service.PubDeviceService;
import com.leesche.zcsp.node.web.service.impl.data.read.PubDeviceDto;
import com.leesche.zcsp.node.web.service.impl.data.read.QueryPubDeviceCondition;
import com.leesche.zcsp.node.web.service.privilege.PrivilegeService;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.File;
import java.io.IOException;
import java.util.Map;

import static com.leesche.zcsp.node.utils.UUIDGenerateUtil.generateShortUuid;

/**
 * Created by kaider on 2016/9/27.
 */
@Controller
@RequestMapping("/web/device")
public class DeviceController
{
    private final static Logger LOGGER = LoggerFactory.getLogger(DeviceController.class);

    private static final String LIST_VIEW = "web/device/listView";
    private static final String DEVICE_LIST_VIEW = "web/device/deviceListView";
    private final static String destPath = PropKit.use("rqcode.properties").get("destPath");
    private final static String zipFileName = UtilDate.getDate();

    @Autowired
    private PubDeviceService deviceService;

    @Autowired
    private PrivilegeService privilegeService;

    @RequestMapping(value = "/listView", method = RequestMethod.GET)
    public String listView()
    {
        return LIST_VIEW;
    }


    @ResponseBody
    @RequestMapping(value = "/list.json", method = RequestMethod.GET)
    public Map<String, Object> listJson(
            final QueryPubDeviceCondition condition
    )
    {
        condition.setAdminId(privilegeService.getCurrentPrincipal().getUserid());
        PagingResult<PubDeviceDto> pagingResult = deviceService.findAllByPage(condition);
        Map<String, Object> json = WebResult.buildOf(pagingResult).toMap();
        return json;
    }

    @RequestMapping(value = "/deviceListView", method = RequestMethod.GET)
    public String deviceListView(){
        return DEVICE_LIST_VIEW;
    }

    @ResponseBody
    @RequestMapping(value = "/deviceList.json", method = RequestMethod.GET)
    public Map<String, Object> deviceListJson(
            final QueryPubDeviceCondition condition
    )
    {
        PagingResult<FactoryDeviceVo> pagingResult = deviceService.selectFactoryDeviceListByPage(condition);
        Map<String, Object> json = WebResult.buildOf(pagingResult).toMap();
        return json;
    }

    /**
     * 执行生成二维码
     * @param vo
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/downCodeZip", method = RequestMethod.POST)
    public Map<String, Object> downCodeZip(
            FactoryDeviceVo vo
    ){
        try {
            makeZipFile(vo.getShortCode(),vo.getPayUrl(),vo.getImme());
            return WebResult.success().toMap();
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            return WebResult.failure(e).toMap();
        }
    }

    /**
     * 下载
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/download", method = RequestMethod.GET)
    public ResponseEntity<byte[]> download() throws IOException {
        Long adminId = privilegeService.getCurrentPrincipal().getUserid();
        File file = new File(destPath+adminId+"/deviceCode/"+zipFileName+"/"+zipFileName+".zip");
        String dfileName = new String(file.getName().getBytes("UTF-8"),"iso-8859-1");
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDispositionFormData("attachment", dfileName);
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED);
    }

    /**
     * 生成设备三码
     * @param shortCode
     * @param payUrl
     * @param imme
     * @throws Exception
     */
    private void makeZipFile(String shortCode,String payUrl,String imme) throws Exception{
        Long adminId = privilegeService.getCurrentPrincipal().getUserid();
        FileToZipUtil.deleteDirectory(destPath+adminId+"/deviceCode");
        //设备简码
        QRCodeUtil.encode(shortCode,destPath+adminId+"/deviceCode/"+zipFileName,true, shortCode);
        //支付码
        QRCodeUtil.encode(payUrl, destPath+adminId+"/deviceCode/"+zipFileName,true, "zf"+shortCode);
        //IMEI码
        QRCodeUtil.encode(imme, destPath+adminId+"/deviceCode/"+zipFileName,true, imme);
        //打包成zip文件
        FileToZipUtil.makeZipFile(destPath+adminId+"/deviceCode/"+zipFileName,zipFileName);
    }

}

/*
    @RequestMapping(value = "/addView", method = RequestMethod.GET)
    public String addView()
    {
        return "device/addView";
    }


    @ResponseBody
    @RequestMapping
    public Map<String, Object> add(
            final PubDevice device
    )
    {
        try {
            device.setAdminid(privilegeService.getCurrentPrincipal().getUserid());
            deviceService.insert(device);
            return WebResult.success().info("操作成功！").toMap();

        } catch (Exception e) {
            LOGGER.error(e.getMessage(),e);
            return WebResult.failure(e).toMap();
        }
    }


    @RequestMapping(value = "/{id}/editView", method = RequestMethod.GET)
    public String editView(
            final @PathVariable("id") Long id,
            final Model model
    )
    {
        PubDevice device = deviceService.selectByPrimaryKey(id);

        model.addAttribute("device", device);

        return "device/editView";
    }


    @ResponseBody
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public Map<String, Object> edit(
            final PubDevice device
    )
    {
        try {
            deviceService.updateByPrimaryKey(device);
            return WebResult.success().info("操作成功").toMap();
        } catch (Exception e) {
            LOGGER.error(e.getMessage(),e);
            return WebResult.failure(e).toMap();
        }
    }


    @ResponseBody
    @RequestMapping(value = "/{id}/delete", method = RequestMethod.POST)
    public Map<String, Object> delete(
            final @PathVariable("id") Long id
    )
    {
        try {
            deviceService.deleteByPrimaryKey(id);
            return WebResult.success().info("操作成功").toMap();
        } catch (Exception e) {
            LOGGER.error(e.getMessage(),e);
            return WebResult.failure(e).toMap();
        }
    }*/
